#include <stdio.h>
#include "fxtexture.h"
#include "game.h"
#include <d3dx9.h>
#pragma comment(lib, "d3dx9.lib")

int FxTexture::beginDrawing() const
{
	UINT passes;
	//effect->SetMatrix("g_mWorldViewProj", Game::getGraphics()->getWorldViewProjectionMatrix());
	effect->SetFloat("g_fTime", Game::getTime());
	if(FAILED(effect->Begin(&passes, 0)))
		return 0;
	return passes;
}

void FxTexture::endDrawing() const
{
	effect->End();
}

void FxTexture::beginPass(int pass) const
{
	if(FAILED(effect->BeginPass(pass)))
	{
		OutputDebugString("");
	}
}

void FxTexture::endPass() const
{
	effect->EndPass();
}

/**
 * Laduje zasob.
 */
bool FxTexture::load()
{
	if(effect)
		unload();

	if(FAILED(D3DXCreateEffect(Game::getGraphics()->getDevice(),
			getData(), getDataSize(), NULL, NULL, 0, NULL,
			&effect, NULL)))
		return false;

	D3DXHANDLE tech;
	if(FAILED(effect->FindNextValidTechnique(NULL, &tech)))
		return false;
	if(FAILED(effect->SetTechnique(tech)))
		return false;


	for(int i = 0; i < 16; i++)
	{
		D3DXHANDLE param;
		D3DXPARAMETER_DESC paramDesc;
		static char buf[128];
		
		param = effect->GetParameter(NULL, i);
		if(!param)
			break;

		if(FAILED(effect->GetParameterDesc(param, &paramDesc)))
		{
			OutputDebugString("GetParameterDesc failed!\n");
			continue;
		}

		sprintf(buf, "param%d: name = '%s', ann = %d\n", i, paramDesc.Name, paramDesc.Annotations);
		OutputDebugString(buf);


		// tekstura?
		if(D3DXPT_TEXTURE == paramDesc.Type)
		{
			LPDIRECT3DBASETEXTURE9 tex = NULL;
			D3DXHANDLE ann;

			// wczytaj annotacje "fileName"
			ann = effect->GetAnnotationByName(param, "fileName");
			if(ann)
			{
				LPCSTR texFileName = NULL;
				if(SUCCEEDED(effect->GetString(ann, &texFileName)))
				{
					// ok, zaladuj teksture
					Texture* t = (Texture*)Game::getResourceManager()->getResourceByName(texFileName);
					if(!t)
						t = (Texture*)Game::getResourceManager()->addResource(texFileName, Resource::TextureResource);
					if(t)
					{
						// wszystko ok :)
						tex = t->getTexture();
					}
				}
			}

			if(tex)
			{
				effect->SetTexture(param, tex);
			}
		}


	}

	return true;
}


/**
 * ...
 */
void FxTexture::unload()
{
	if(effect)
	{
		effect->Release();
		effect = NULL;
	}
}
